#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
from django import forms
from django.forms import fields
from django.forms import widgets
from django.forms.models import ModelChoiceField
from repoistory import models


class ProjectCreateForm(forms.Form):
    '''新建Git项目'''
    name = fields.CharField(label='项目名',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入项目名')
    description = fields.CharField(label='描述',
                               widget=widgets.TextInput(attrs={'class': 'form-control'}),
                               required=False)
    git_address = fields.CharField(label='Git地址',
                               widget=widgets.TextInput(attrs={'class': 'form-control',
                                                               'placeholder':'https://xx.xx.com/xx.git'}),
                               required='请输入项目的Git地址')

    auth = ModelChoiceField(label='Git账号',
                            queryset=models.Auth.objects.all(),    # 传入queryset
                            to_field_name='id',    # 使用指定的字段作为value
                            widget=widgets.Select(attrs={'class': 'form-control'}),)

    def clean_name(self):
        if models.Project.objects.filter(name=self.cleaned_data['name']).exists():
            self.add_error('name','项目名称已存在')
        else:
            return self.cleaned_data['name']


class ProjectEditForm(forms.Form):
    '''修改Git项目'''
    id = fields.CharField(widget=widgets.HiddenInput(), label='')
    name = fields.CharField(label='项目名',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入项目名')
    description = fields.CharField(label='描述',
                               widget=widgets.TextInput(attrs={'class': 'form-control'}),
                               required=False)
    git_address = fields.CharField(label='Git地址',
                               widget=widgets.TextInput(attrs={'class': 'form-control',
                                                               'placeholder':'https://xx.xx.com/xx.git'}),
                               required='请输入项目的Git地址')

    auth = ModelChoiceField(label='Git账号',
                            queryset=models.Auth.objects.all(),    # 传入queryset
                            to_field_name='id',    # 使用指定的字段作为value
                            widget=widgets.Select(attrs={'class': 'form-control'}),)

    def clean_name(self):
        if models.Project.objects.filter(name=self.cleaned_data['name']).exclude(id=self.cleaned_data['id']).exists():
            self.add_error('name','项目名称已存在')
        else:
            return self.cleaned_data['name']


class AuthCreateForm(forms.Form):
    '''新增Git账号form验证'''
    name = fields.CharField(label='Git账号',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入Git账号')
    password = fields.CharField(label='Git密码',
                                widget=widgets.PasswordInput(attrs={'class': 'form-control'}),
                                required='请输入Git密码')

    def clean(self):
        if models.Auth.objects.filter(name=self.cleaned_data['name'],password=self.cleaned_data['password']).exists():
            self.add_error('__all__','已存在相同账号')
        else:
            return self.cleaned_data


class AuthEditForm(forms.Form):
    '''修改Git账号form验证'''
    id = fields.CharField(widget=widgets.HiddenInput(),label='')
    name = fields.CharField(label='Git账号',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入Git账号')
    password = fields.CharField(label='Git密码',
                                widget=widgets.PasswordInput(attrs={'class': 'form-control'}),
                                required='请输入Git密码')

    def clean(self):
        if models.Auth.objects.filter(name=self.cleaned_data['name'],password=self.cleaned_data['password']).exclude(id=self.cleaned_data['id']).exists():
            self.add_error('__all__','已存在相同账号')
        else:
            return self.cleaned_data


class BranchCreateForm(forms.Form):
    '''新建Branch'''
    project_id = fields.CharField(widget=widgets.HiddenInput(), label='')
    branch = fields.CharField(label='Branch',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入Branch')
    description = fields.CharField(label='描述',
                                   widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                   required=False)

    def clean_branch(self):
        if not self.cleaned_data['project_id'] or not models.Project.objects.filter(id=self.cleaned_data['project_id']).exists():
            self.add_error('branch', '数据异常，项目不存在')
        elif models.Branch.objects.filter(branch=self.cleaned_data['branch'],project_id=self.cleaned_data['project_id']).exists():
            self.add_error('branch', '已存在相同分支')
        else:
            return self.cleaned_data['branch']


class BranchEditForm(forms.Form):
    '''修改Branch'''
    id = fields.CharField(widget=widgets.HiddenInput(), label='')
    project_id = fields.CharField(widget=widgets.HiddenInput(), label='')
    branch = fields.CharField(label='Branch',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入Branch')
    description = fields.CharField(label='描述',
                                   widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                   required=False)

    def clean_branch(self):
        if not self.cleaned_data['project_id'] or not models.Project.objects.filter(id=self.cleaned_data['project_id']).exists():
            self.add_error('branch', '数据异常，项目不存在')
        elif models.Branch.objects.filter(branch=self.cleaned_data['branch'],project_id=self.cleaned_data['project_id']).exclude(id=self.cleaned_data['id']).exists():
            self.add_error('branch', '已存在相同分支')
        else:
            return self.cleaned_data['branch']


class SubModulCreateForm(forms.Form):
    '''新增子模块'''
    name = fields.CharField(label='模块名',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入模块名')
    order = fields.IntegerField(label='更新顺序',min_value=1,
                                widget=widgets.NumberInput(attrs={'class': 'form-control'}),
                                error_messages={'required:': '请输入更新顺序',
                                                'invalid': '格式错误',
                                                'min_length': '最小为1'})

    description = fields.CharField(label='模块描述',
                                widget=widgets.TextInput(attrs={'class': 'form-control'}),required=False)
    source_file = fields.CharField(label='打包后文件路径',
                                widget=widgets.TextInput(attrs={'class': 'form-control',
                                                                ' placeholder':'如:$REPOSITORY/xxx/xxx.war'}),
                                                        required='请填写文件路径')
    target_file = fields.CharField(label='目标服务器上路径',
                                widget=widgets.TextInput(attrs={'class': 'form-control',
                                                                ' placeholder':'如:/xxx/xxx.war'}),
                                                        required='请填写文件路径')
    backup_command = fields.CharField(label='备份命令',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    stop_command = fields.CharField(label='停止服务命令',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    start_command = fields.CharField(label='启动服务命令',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    clean_old_file_command = fields.CharField(label='清理旧文件命令',
                                     widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                     required=False)

    project_id = fields.CharField(widget=widgets.HiddenInput(), label='')

    def clean(self):
        if models.SubModul.objects.filter(name=self.cleaned_data['name'],project_id=self.cleaned_data['project_id']).exists():
            self.add_error('name','已存在相同子模块')
        else:
            return self.cleaned_data


class SubModulEditForm(forms.Form):
    '''修改子模块'''
    name = fields.CharField(label='模块名',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required='请输入模块名')
    order = fields.IntegerField(label='更新顺序',min_value=1,
                                widget=widgets.NumberInput(attrs={'class': 'form-control'}),
                                error_messages={'required:': '请输入更新顺序',
                                                'invalid': '格式错误',
                                                'min_length': '最小为1'})
    description = fields.CharField(label='模块描述',
                                widget=widgets.TextInput(attrs={'class': 'form-control'}),required=False)
    source_file = fields.CharField(label='打包后文件路径',
                                widget=widgets.TextInput(attrs={'class': 'form-control',
                                                                ' placeholder':'如:$REPOSITORY/xxx/xxx.war'}),
                                                        required='请填写文件路径')
    target_file = fields.CharField(label='目标服务器上路径',
                                widget=widgets.TextInput(attrs={'class': 'form-control',
                                                                ' placeholder':'如:/xxx/xxx.war'}),
                                                        required='请填写文件路径')
    backup_command = fields.CharField(label='备份命令',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    stop_command = fields.CharField(label='停止服务命令',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    start_command = fields.CharField(label='启动服务命令',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    clean_old_file_command = fields.CharField(label='清理旧文件命令',
                                     widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                     required=False)
    id = fields.CharField(widget=widgets.HiddenInput(), label='')
    project_id = fields.CharField(widget=widgets.HiddenInput(), label='')

    def clean(self):
        if models.SubModul.objects.filter(name=self.cleaned_data['name'],project_id=self.cleaned_data['project_id'])\
                .exclude(id=self.cleaned_data['id']).exists():
            self.add_error('name','已存在相同子模块')
        else:
            return self.cleaned_data


class ConfigrationCreateForm(forms.Form):
    '''新增配置文件'''
    file_path = fields.CharField(label='配置文件路径',
                                 widget=widgets.TextInput(attrs={'class': 'form-control',
                                                                 'placeholder': '如:$REPOSITORY/xxx/xxx.conf'}),
                                 required='请输入配置文件路径')
    file_type = fields.CharField(label='文件类型',
                            widget=widgets.TextInput(attrs={'class': 'form-control',
                                                            ' placeholder': '如:yml、xml'}),
                            required='请输入配置文件路径')
    description = fields.CharField(label='文件描述',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    config = fields.CharField(label='配置',
                            widget=widgets.Textarea(attrs={'class': 'form-control','rows': 15,'id':'textarea'}))

    submodul_id = fields.CharField(widget=widgets.HiddenInput(), label='')

    def clean(self):
        if models.Configuration.objects.filter(file_path=self.cleaned_data['file_path'],submodul_id=self.cleaned_data['submodul_id']).exists():
            self.add_error('file_path','已存在相同配置文件')
        else:
            return self.cleaned_data


class ConfigrationEditForm(forms.Form):
    '''修改配置文件'''
    file_path = fields.CharField(label='配置文件路径',
                                 widget=widgets.TextInput(attrs={'class': 'form-control',
                                                                 'placeholder': '如:$REPOSITORY/xxx/xxx.conf'}),
                                 required='请输入配置文件路径')
    file_type = fields.CharField(label='文件类型',
                            widget=widgets.TextInput(attrs={'class': 'form-control',
                                                            ' placeholder': '如:yml、xml'}),
                            required='请输入配置文件路径')
    description = fields.CharField(label='文件描述',
                            widget=widgets.TextInput(attrs={'class': 'form-control'}),
                            required=False)
    config = fields.CharField(label='配置',
                            widget=widgets.Textarea(attrs={'class': 'form-control','rows': 15,'id':'textarea'}))

    submodul_id = fields.CharField(widget=widgets.HiddenInput(), label='')
    id = fields.CharField(widget=widgets.HiddenInput(), label='')

    def clean(self):
        if models.Configuration.objects.filter(file_path=self.cleaned_data['file_path'],
                        submodul_id=self.cleaned_data['submodul_id']).exclude(id=self.cleaned_data['id']).exists():
            self.add_error('file_path','已存在相同配置文件')
        else:
            return self.cleaned_data


class HostCreateForm(forms.Form):
    '''新增服务器'''
    ip_address = fields.GenericIPAddressField(label='IP地址',
                                              widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                              error_messages={'required:': '请输入服务器地址',
                                                              'invalid': '不是有效的IP地址'},)
    ssh_port = fields.IntegerField(label='SSH端口',min_value=1,max_value=65535,
                                   widget=widgets.NumberInput(attrs={'class': 'form-control'}),
                                   error_messages={'required:': '请输入ssh端口',
                                                                               'invalid': '格式错误',
                                                                               'min_length':'格式错误',
                                                                               'max_length':'格式错误'})
    ssh_user = fields.CharField(label='SSH用户',
                                widget=widgets.TextInput(attrs={'class': 'form-control',
                                                            'value': 'root',
                                                            'disabled': 'disabled'}),
                            required=False)
    ssh_password = fields.CharField(label='SSH密码',
                            widget=widgets.PasswordInput(attrs={'class': 'form-control'}),
                            required='请输入SSH密码')
    description = fields.CharField(label='服务器描述',
                                   widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                   required=False
                                   )
    def clean_ssh_user(self):
        return 'root'

    def clean(self):
        if self.cleaned_data.get('ip_address'):
            if models.Host.objects.filter(ip_address=self.cleaned_data.get('ip_address')).exists():
                self.add_error('ip_address','该服务器已存在')
            else:
                return self.cleaned_data


class HostEditForm(forms.Form):
    '''修改服务器'''
    ip_address = fields.GenericIPAddressField(label='IP地址',
                                              widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                              error_messages={'required:': '请输入服务器地址',
                                                              'invalid': '不是有效的IP地址'},)
    ssh_port = fields.IntegerField(label='SSH端口',min_value=1,max_value=65535,
                                   widget=widgets.NumberInput(attrs={'class': 'form-control'}),
                                   error_messages={'required:': '请输入ssh端口',
                                                                               'invalid': '格式错误',
                                                                               'min_length':'格式错误',
                                                                               'max_length':'格式错误'})
    ssh_user = fields.CharField(label='SSH用户',
                                widget=widgets.TextInput(attrs={'class': 'form-control',
                                                            'value': 'root',
                                                            'disabled': 'disabled'}),
                            required=False)
    ssh_password = fields.CharField(label='SSH密码',
                            widget=widgets.PasswordInput(attrs={'class': 'form-control'}),
                            required='请输入SSH密码')
    description = fields.CharField(label='服务器描述',
                                   widget=widgets.TextInput(attrs={'class': 'form-control'}),
                                   required=False
                                   )
    id = fields.CharField(widget=widgets.HiddenInput(), label='')
    def clean_ssh_user(self):
        return 'root'

    def clean(self):
        if self.cleaned_data.get('ip_address'):
            if models.Host.objects.filter(ip_address=self.cleaned_data.get('ip_address')).exclude(id=self.cleaned_data['id']).exists():
                self.add_error('ip_address','该服务器已存在')
            else:
                return self.cleaned_data


class SubModul2HostCreateForm(forms.Form):
    '''新增子模块关联主机'''
    submodul_id = fields.CharField(widget=widgets.HiddenInput(), label='')
    host = ModelChoiceField(
        label='请选择服务器',
        widget=widgets.Select(attrs={'class': 'selectpicker'}),
        queryset=models.Host.objects.all(),  # 传入queryset
        empty_label='------',  # 自定义空白栏
        required='请选择服务器',
    )
    is_customize = fields.CharField(widget=widgets.CheckboxInput(),label='是否单独配置',required=False)


    source_file = fields.CharField(label='打包后文件路径',
                                   widget=widgets.TextInput(attrs={'class': 'form-control customize',
                                                                   ' placeholder': '如:$REPOSITORY/xxx/xxx.war',
                                                                   'disabled':'disabled'}),
                                   required='请填写文件路径')
    target_file = fields.CharField(label='目标服务器上路径',
                                   widget=widgets.TextInput(attrs={'class': 'form-control customize',
                                                                   ' placeholder': '如:/xxx/xxx.war',
                                                                   'disabled': 'disabled'}),
                                   required='请填写文件路径')
    backup_command = fields.CharField(label='备份命令',
                                      widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                      required=False)
    stop_command = fields.CharField(label='停止服务命令',
                                    widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                    required=False)
    start_command = fields.CharField(label='启动服务命令',
                                     widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                     required=False)
    clean_old_file_command = fields.CharField(label='清理旧文件命令',
                                     widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                     required=False)


class SubModul2HostEditForm(forms.Form):
    '''新增子模块关联主机'''
    submodul_id = fields.CharField(widget=widgets.HiddenInput(), label='')
    host = ModelChoiceField(
        label='请选择服务器',
        widget=widgets.Select(attrs={'class': 'selectpicker'}),
        queryset=models.Host.objects.all(),  # 传入queryset
        empty_label='------',  # 自定义空白栏
        required='请选择服务器',
    )
    is_customize = fields.CharField(widget=widgets.CheckboxInput(),label='是否单独配置',required=False)


    source_file = fields.CharField(label='打包后文件路径',
                                   widget=widgets.TextInput(attrs={'class': 'form-control customize',
                                                                   ' placeholder': '如:$REPOSITORY/xxx/xxx.war',
                                                                   'disabled':'disabled'}),
                                   required='请填写文件路径')
    target_file = fields.CharField(label='目标服务器上路径',
                                   widget=widgets.TextInput(attrs={'class': 'form-control customize',
                                                                   ' placeholder': '如:/xxx/xxx.war',
                                                                   'disabled': 'disabled'}),
                                   required='请填写文件路径')
    backup_command = fields.CharField(label='备份命令',
                                      widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                      required=False)
    stop_command = fields.CharField(label='停止服务命令',
                                    widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                    required=False)
    start_command = fields.CharField(label='启动服务命令',
                                     widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                     required=False)
    clean_old_file_command = fields.CharField(label='清理旧文件命令',
                                     widget=widgets.TextInput(attrs={'class': 'form-control customize','disabled':'disabled'}),
                                     required=False)
    id = fields.CharField(widget=widgets.HiddenInput(), label='')